package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.GeneralStorage;
import com.kang.pojo.GeneralStorage_itemInformation;
import com.kang.pojo.GgeneralStoragePoJo;
import com.kang.pojo.IntemInformation;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.Warehouse;
import com.kang.service.AssistService;
import com.kang.service.GeneralStorage_itemInformationService;
import com.kang.service.GeneralstorageService;
import com.kang.service.IntemInformationService;
import com.kang.service.ItemDetailService;
import com.kang.service.SupplierService;
import com.kang.service.UserService;
import com.kang.service.WarehouseService;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.GeneralStoragePage;
import com.vonechina.entity.page.ItemPage;
import com.vonechina.entity.page.WareHouseOrderPage;

import jxl.Sheet;
import jxl.Workbook;

/**
 * 普通入库管理
 * 
 * @author ysq
 *
 */
@Controller
@RequestMapping("generalStorage")
@SessionAttributes({ "generalStoragePage" })
public class GeneralStorageController extends com.kang.controller.Controller {
	/**
	 * 普通入库服务
	 */
	@Resource
	private GeneralstorageService gls;
	/**
	 * 普通入库-物品服务
	 */
	@Resource
	private GeneralStorage_itemInformationService gl_ifs;
	/**
	 * 用户管理服务
	 */
	@Resource
	private UserService users;
	/**
	 * 物品服务
	 */
	@Resource
	private IntemInformationService itemService;
	/**
	 * 仓库服务
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 通用服务
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 供应商服务
	 */
	@Resource
	private SupplierService supplierService;
	/**
	 * 物品批次服务
	 */
	@Resource
	private ItemDetailService itemDetailService;

	/**
	 * 根据generalstorageid删除generalstorage
	 * 
	 * @param generalstorageid
	 * @return
	 */
	@RequestMapping("delGeneralStorage")
	@ResponseBody
	public String deletePickingreturn(Integer generalstorageid) {
		AjaxResult result = new AjaxResult();
		// 根据generalstorageid删除generalstorage
		int a = gls.delGeneralStorage(generalstorageid);
		// 根据generalstorageid删除所有GeneralStorage_itemInformation信息
		int b = gl_ifs.deleteByGeneralStorageID(generalstorageid);
		if (a > 0 && b > 0) {
			result.setResult("success");
		} else {
			result.setResult("fail");
		}

		return JSON.toJSONString(result);
	}

	/**
	 * 查询物品(用于新增普通入库-添加商品)
	 * 
	 * @param itemPage
	 * @return
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(ItemPage itemPage) {
		List<IntemInformation> iteminfolist = itemService
				.listNotInItem(itemPage);
		AjaxResult result = new AjaxResult();
		result.setRows(iteminfolist);
		result.setTotal(itemPage.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 去到查看普通入库详情
	 * 
	 * @param model
	 * @param generalstorageid
	 * @return
	 */
	@RequestMapping("toDetailsGeneralStorage")
	public String toDetailsGeneralStorage(Model model, int generalstorageid) {
		model.addAttribute("supplierList", supplierService.listAllSupplier());// 查询供应商
		// 根据generalStorageID查询generalstorage数据
		GeneralStorage gs1 = gls.selectByGeneralStorage(generalstorageid);// 查询普通入库信息
		// 查询数据根据GeneralStorage_itemInformation
		List<GeneralStorage_itemInformation> list1 = gl_ifs
				.selectGeneralStorage_itemInformationByGeneralstorageid(generalstorageid);

		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		int list1Sum = list1.size();
		for (int i = 0; i < list1Sum; i++) {
			// 查询物品信息根据inteminformationid
			IntemInformation iif1 = itemService.selectByID(list1.get(i)
					.getIteminformationid());

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("IntemInformation", iif1);
			map1.put("GeneralStorage_itemInformation", list1.get(i));
			list2.add(map1);
		}

		model.addAttribute("gs1", gs1);
		model.addAttribute("list2", list2);

		model.addAttribute("purchaser",
				users.getUserById(gs1.getPurchaserid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("createPerson",
				users.getUserById(gs1.getCreatepersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastModified",
				users.getUserById(gs1.getLastmodifiedid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库
		return "storage/normalStorage/detailsGeneralStorage";
	}

	/**
	 * 去到修改普通入库
	 * 
	 * @param session
	 * @param model
	 * @param generalstorageid
	 * @return
	 */
	@RequestMapping("toUpdate")
	public String updateGeneralStorage(HttpSession session, Model model,
			int generalstorageid) {
		initRight(session);
		if (checkRight("编辑全部采购入库") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("supplierList", supplierService.listAllSupplier());// 查询供应商
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		GeneralStorage gs1 = gls.selectByGeneralStorage(generalstorageid);// 根据generalStorageID查询generalstorage数据
		// 查询数据根据GeneralStorage_itemInformation
		List<GeneralStorage_itemInformation> list1 = gl_ifs
				.selectGeneralStorage_itemInformationByGeneralstorageid(generalstorageid);
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		int list1Sum = list1.size();
		for (int i = 0; i < list1Sum; i++) {
			// 查询物品信息根据inteminformationid
			IntemInformation iif1 = itemService.selectByID(list1.get(i)
					.getIteminformationid());

			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("IntemInformation", iif1);
			map1.put("GeneralStorage_itemInformation", list1.get(i));

			list2.add(map1);
		}

		model.addAttribute("purchaser",
				users.getUserById(gs1.getPurchaserid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("createPerson",
				users.getUserById(gs1.getCreatepersonid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastModified",
				users.getUserById(gs1.getLastmodifiedid() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("gs1", gs1);
		model.addAttribute("list2", list2);
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库

		return "storage/normalStorage/updateGeneralStorage";
	}

	/**
	 * 修改普通入库
	 * 
	 * @param gs
	 * @param itemIds
	 * @param itemNumber
	 * @param expiryDate
	 * @param itemDetailId
	 * @param generalStorageItemInformationId
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updatePurchaseRequest(GeneralStorage gs, Integer[] itemIds,
			Integer[] itemNumber, String[] expiryDate, String[] itemDetailId,
			String[] generalStorageItemInformationId) {

		AjaxResult result = new AjaxResult();
		gs.setCreatedate(new Date());
		gs.setLastmodifiedtime(new Date());
		gls.updateByPrimaryKeySelective(gs);// 修改普通入库信息

		// 删除该普通入库单id下的所有GeneralStorage_itemInformation
		gl_ifs.deleteByGeneralStorageID(gs.getGeneralstorageid());

		// 重新插入修改后的GeneralStorage_itemInformation
		for (int i = 0; i < itemIds.length; i++) {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = new Date();
			try {
				date1 = sdf1.parse(expiryDate[i]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			GeneralStorage_itemInformation gi1 = new GeneralStorage_itemInformation();
			gi1.setExpiryDate(date1);
			gi1.setGeneralstorageid(gs.getGeneralstorageid());
			gi1.setIteminformationid(itemIds[i]);
			gi1.setStoragequantity(itemNumber[i]);
			gi1.setWarehouseid(gs.getWarehouseid());

			gl_ifs.insertone(gi1);// 插入GeneralStorage_itemInformation

			// 如果是提交状态那就提交以及更改库存
			if ("1".equals(gs.getStatus().trim())) {
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				itemService.updateIntemInformationCurrentStock(i2);// 修改库存

				// 插入item_detail
				ItemDetail itemDetail1 = new ItemDetail();
				itemDetail1.setItemInformationID(itemIds[i]);
				itemDetail1.setBatchNumber(itemDetailService
						.generateBatchNumber());

				itemDetail1.setExpiryDate(date1);
				itemDetail1.setNumber(itemNumber[i]);
				itemDetail1.setWarehouseManagementID(gs.getWarehouseid());
				itemDetail1.setStatus(0);// 0正常
				itemDetail1.setSource_type(0);// 入库类型 0普通入库 1采购入库
				itemDetail1.setSource_id(gi1.getId());
				itemDetailService.addItemDetail(itemDetail1);
			}
		}
		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 去到添加普通入库
	 * 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("toAdd")
	public String addGeneralStorage(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增普通入库") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("supplierList", supplierService.listAllSupplier());// 查询供应商
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "storage/normalStorage/addGeneralStorage";
	}

	/**
	 * 添加普通入库
	 * 
	 * @param gs
	 * @param itemIds
	 * @param itemNumber
	 * @param expiryDate
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addPurchaseRequest(GeneralStorage gs, Integer[] itemIds,
			Integer[] itemNumber, String[] expiryDate) {
		AjaxResult result = new AjaxResult();
		gs.setWarehousenumber(gls.selectMaxWarehouseNumber());// 生成普通入库编号
		gs.setCreatedate(new Date());
		gs.setLastmodifiedtime(new Date());
		gls.insertone(gs);// 保存普通入库信息
		GeneralStorage gs2 = gls.selectoneid(gs.getWarehousenumber());// 根据warehousenumber查询generalstorage
		if (gs2.getCreatepersonid() == null || gs2.getCreatepersonid() <= 0) {
			return JSON.toJSONString(result);
		}
		for (int i = 0; i < itemIds.length; i++) {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = new Date();
			try {
				date1 = sdf.parse(expiryDate[i]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			GeneralStorage_itemInformation gi1 = new GeneralStorage_itemInformation();
			gi1.setExpiryDate(date1);
			gi1.setGeneralstorageid(gs2.getGeneralstorageid());
			gi1.setIteminformationid(itemIds[i]);
			gi1.setStoragequantity(itemNumber[i]);
			gi1.setWarehouseid(gs2.getWarehouseid());
			gl_ifs.insertone(gi1);// 保存GeneralStorage_itemInformation

			// 如果是提交状态那就提交以及更改库存
			if ("1".equals(gs.getStatus().trim())) {
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				itemService.updateIntemInformationCurrentStock(i2);// 修改库存

				// 插入item_detail
				ItemDetail itemDetail1 = new ItemDetail();
				itemDetail1.setItemInformationID(itemIds[i]);
				itemDetail1.setBatchNumber(itemDetailService
						.generateBatchNumber());

				itemDetail1.setExpiryDate(date1);
				itemDetail1.setNumber(itemNumber[i]);
				itemDetail1.setWarehouseManagementID(gs.getWarehouseid());
				itemDetail1.setStatus(0);// 0正常
				itemDetail1.setSource_type(0);// 入库类型 0普通入库 1采购入库
				itemDetail1.setSource_id(gi1.getId());
				itemDetailService.addItemDetail(itemDetail1);
			}
		}

		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 普通入库表数据查询分页
	 * 
	 * @param session
	 * @param model
	 * @param generalStoragePage
	 * @return
	 */
	@RequestMapping("selectByWhere")
	public String generalStorageByWhere(HttpSession session, Model model,
			GeneralStoragePage generalStoragePage) {
		initRight(session);
		if (checkRight("查看普通入库") != SUCCESS
				&& checkRight("查看全部普通入库") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部普通入库") == SUCCESS) {
			generalStoragePage.setSubnameId(null);
		} else {
			generalStoragePage.setSubnameId(userID + "");
		}
		List<GgeneralStoragePoJo> gsp = gls.selectByWheres(generalStoragePage);// 查询普通入库数据集合
		List<Warehouse> wm = warehouseService.listAllWarehouse();
		model.addAttribute("wm", wm);
		model.addAttribute("gsp", gsp);

		generalStoragePage.setPageUrl("generalStorage/selectByWhere.do");
		model.addAttribute("page", generalStoragePage);
		return "storage/normalStorage/listGeneralStorage";
	}
	
	/**
	 * 导出普通入库PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, String warehousenumber, GeneralStoragePage generalStoragePage)
			throws Exception {
		//System.out.println("=============导出采购入库PDF文件===============");
		GeneralStorage gStorage = gls.selectoneid(warehousenumber);
		List<GgeneralStoragePoJo> gsList = gls.selectByWheres(generalStoragePage);// 查询采购入库数据集合
		System.out.println("======warehouseOrder========"+generalStoragePage);
		System.out.println("======woList========"+gsList);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = StoragePDF.NormalStoragePDF(gStorage, gsList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	
	
	
	
	
	
	
	
	/**
	 * 导入excel
	 */
	@RequestMapping("importfile")
	public void execlImport(@RequestParam("fileExcle_name") MultipartFile excleFile,
			HttpSession session,ModelMap model,HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setCharacterEncoding("utf-8"); 
		response.setContentType("text/html;charset=utf-8"); 
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		if(excleFile!=null && !excleFile.isEmpty()){
        	String fileName = excleFile.getOriginalFilename();//文件名称
        	System.out.println("fileName:"+fileName);
        	//根据指定的文件输入流导入Excel从而产生Workbook对象
    		Workbook wb = null;
    		System.out.println("进入这个方法");
    		try {
    			wb = Workbook.getWorkbook(excleFile.getInputStream());
    		} catch (Exception e) {
    			e.printStackTrace();
    			out.print("<script>alert('文件格式错误，请使用xls为后缀的文件进行导入');</script>");
    			System.out.println("格式排查出问题，请在本地建一份excle文件，在将数据导入");	
    		}
    		Sheet sht0 = wb.getSheet(0);
    		int romSize = sht0.getRows();
    		if(romSize > 0) {
    			if(insertExceldata(sht0,out,romSize)) {
    				out.print("<script>alert('导入成功');location.href='"+basePath+"listGeneralStorage.jsp';</script>");
    			}
    			else {
    				out.print("<script>alert('导入失败');history.back();</script>");
    			}
    			out.close();
    		}
		}
	}
	
	/**
	 * 插入excel数据
	 */
	private boolean insertExceldata(Sheet sht0,PrintWriter out,int romSize) {
		boolean statu = false;
		List<GgeneralStoragePoJo> list=new ArrayList<GgeneralStoragePoJo>();
		GgeneralStoragePoJo GgeneralStoragePoJo = null;
		for(int i = 0; i < romSize; i++) {
			if(i==0){//根据具体数据而定,第一行为标题,需要忽略
				continue;
			}
			if(sht0.getCell(0, i).getContents().trim() == null
					|| "".equals(sht0.getCell(0, i).getContents().trim())){
				continue;
			}
			GeneralStorage_itemInformation gi1 = new GeneralStorage_itemInformation();
			//实例化一个对象然后将要导入的一条数据存入其中
			String generalstorageid = sht0.getCell(0, i).getContents().trim();
			String warehouseid = sht0.getCell(1, i).getContents().trim();
			String iteminformationid = sht0.getCell(2, i).getContents().trim();
			String storagequantity = sht0.getCell(3, i).getContents().trim();
			String expiryDate = sht0.getCell(4, i).getContents().trim();
			
			gi1.setWarehouseid(Integer.parseInt(warehouseid));
			gi1.setIteminformationid(Integer.parseInt(iteminformationid));
			gi1.setStoragequantity(Integer.parseInt(storagequantity));
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			try {
				gi1.setExpiryDate(sdf.parse(expiryDate));
			} catch (ParseException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
		}
		return statu;
	}
	
	/**
	 * 导出
	 */
	@RequestMapping("outputfile")
	public void execloutput(@RequestParam("fileExcle_name") MultipartFile excleFile,
			HttpSession session,ModelMap model,HttpServletRequest request, HttpServletResponse response) throws Exception{
		response.setCharacterEncoding("utf-8"); 
		response.setContentType("text/html;charset=utf-8"); 
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		if(excleFile!=null && !excleFile.isEmpty()){
        	String fileName = excleFile.getOriginalFilename();//文件名称
        	System.out.println("fileName:"+fileName);
        	//根据指定的文件输入流导入Excel从而产生Workbook对象
    		Workbook wb = null;
    		System.out.println("进入这个方法");
    		try {
    			wb = Workbook.getWorkbook(excleFile.getInputStream());
    		} catch (Exception e) {
    			e.printStackTrace();
    			out.print("<script>alert('文件格式错误，请使用xls为后缀的文件进行导入');</script>");
    			System.out.println("格式排查出问题，请在本地建一份excle文件，在将数据导入");	
    		}
    		Sheet sht0 = wb.getSheet(0);
    		int romSize = sht0.getRows();
    		if(romSize > 0) {
    			if(insertExceldata(sht0,out,romSize)) {
    				out.print("<script>alert('导出成功');location.href='"+basePath+"listGeneralStorage.jsp';</script>");
    			}
    			else {
    				out.print("<script>alert('导入失败');history.back();</script>");
    			}
    			out.close();
    		}
		}
	}
}
